/**
 * 
 */
package com.pos.modules.inquery;

import android.content.res.Configuration;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.basewin.aidl.OnPrinterListener;
import com.basewin.services.ServiceManager;
import com.pos.BaseActivity;
import com.pos.R;
import com.pos.modules.cashier.AccountActivity;
import com.pos.modules.inquery.adapter.BillGoodsListAdapter;
import com.pos.modules.inquery.bean.BillGoodsBean;
import com.pos.net.base.Request.Method;
import com.pos.net.netparam.NetParams;
import com.pos.net.netparam.RequestUrls;
import com.pos.net.request.interfa.BaseRequestListener;
import com.pos.net.request.interfa.JsonRequestListener;
import com.pos.toolbox.FinancialUtils;
import com.pos.widgets.ActionBarManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zng.common.PrintPowerOnAndOffUtils;
import com.zng.common.PrintUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:交易详情
 * @author cai
 * @time:2017年10月16日下午8:59:31
 */
public class BillDetailActivity extends BaseActivity {
	private TextView text_print, text_orderCode, text_orderDatetime, text_goodsCount, text_totalAmount,
			text_actTotalAmount, text_discountAmount;
	private ListView listView;
	private String orderCode;
	private List<BillGoodsBean> billGoodsList = new ArrayList<>();
	private BillGoodsListAdapter adapter;
	private Gson gson = new Gson();
	JSONObject printJson = new JSONObject();
	private StringBuffer sb = new StringBuffer("");
	private PrinterListener printer_callback = new PrinterListener();
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	public class PrinterListener implements OnPrinterListener {

		@Override
		public void onStart() {
			// TODO 打印开始
			// Print start
			// Log.d(TAG, getStr(R.string.print_start));
			// sb.append(getStr(R.string.print_start) + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onStart");
		}

		@Override
		public void onFinish() {
			// TODO 打印结束
			// End of the print
			// Log.d(TAG, getStr(R.string.print_end));
			// sb.append(getStr(R.string.print_end) + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onFinish");

		}

		@Override
		public void onError(int errorCode, String detail) {
			// TODO 打印出错
			// print error
			// Log.d(TAG, getStr(R.string.print_error) + " errorcode = " +
			// errorCode + " detail = " + detail);
			// sb.append(getStr(R.string.print_error) + errorCode + " detail = "
			// + detail + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onError " + detail);

		}
	};
	@Override
	public void initView() {
		setContentView(R.layout.bill_detail_layout);
		text_print = bindId(R.id.text_print);
		text_orderCode = bindId(R.id.text_orderCode);
		text_orderDatetime = bindId(R.id.text_orderDatetime);
		text_goodsCount = bindId(R.id.text_goodsCount);
		text_totalAmount = bindId(R.id.text_totalAmount);
		text_actTotalAmount = bindId(R.id.text_actTotalAmount);
		text_discountAmount = bindId(R.id.text_discountAmount);
		listView = bindId(R.id.listView);
	}

	@Override
	public void initData() {
		ActionBarManager.init(this, "交易详情", true, null, null);
		orderCode = getIntent().getStringExtra("orderCode");
		netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posQueryOrderDetail, Method.POST,
				NetParams.posQueryOrderDetail(mContext, orderCode), 0, listener);

	}

	@Override
	public void initListener() {
		text_print.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posGetOrderPrintInfo, Method.POST,
						NetParams.posGetOrderPrintInfo(mContext, orderCode), 1, listener);
			}
		});

	}

	private BaseRequestListener listener = new JsonRequestListener() {

		@Override
		public void onStart(int requestId) {
			showDialg();
		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			disMissDialog();
			dealError(errorCode, errorMsg);
		}

		@Override
		public void onSuccess(int requestId, String url, JSONObject jsonResult) {
			disMissDialog();
			Log.e("TAG", "onSuccess: "+jsonResult.toString() );
			int retCode = jsonResult.optInt("retCode", 0);

			if (requestId == 0) {
				if (retCode == 1) {
					showShortToast("查询交易详情失败");
					return;
				}
				text_orderCode.setText(jsonResult.optString("orderCode"));
				text_orderDatetime.setText(jsonResult.optString("orderDatetime"));
				text_goodsCount.setText(jsonResult.optString("goodsCount"));
				text_totalAmount.setText(FinancialUtils.fenToYuan(jsonResult.optLong("totalAmount", 0)));
				text_actTotalAmount.setText(FinancialUtils.fenToYuan(jsonResult.optLong("actTotalAmount", 0)));
				text_discountAmount.setText(FinancialUtils.fenToYuan(jsonResult.optLong("discountAmount", 0)));

				JSONArray goodsList = jsonResult.optJSONArray("goodsList");
				if (goodsList == null || goodsList.length() == 0) {
				//	showShortToast("暂无记录");
					listView.setVisibility(View.GONE);
					text_orderCode = bindId(R.id.text_orderCode);
					text_orderDatetime = bindId(R.id.text_orderDatetime);
					text_goodsCount = bindId(R.id.text_goodsCount);
					text_totalAmount = bindId(R.id.text_totalAmount);
					text_actTotalAmount = bindId(R.id.text_actTotalAmount);
					text_discountAmount = bindId(R.id.text_discountAmount);

//					text_orderCode.setText("");
//					text_orderDatetime.setText("");
//					text_goodsCount.setText("0");
//					text_totalAmount.setText("0");
//					text_actTotalAmount.setText("0");
//					text_discountAmount.setText("0");

					return;
				}
				listView.setVisibility(View.VISIBLE);
				billGoodsList = gson.fromJson(goodsList.toString(), new TypeToken<List<BillGoodsBean>>() {
				}.getType());
				adapter = new BillGoodsListAdapter(mContext, billGoodsList);
				listView.setAdapter(adapter);

			} else if (requestId == 1) {
				if (retCode == 1) {
					showShortToast("获取订单信息失败");
					return;
				}
				String printInfo = jsonResult.optString("printInfo");
				startPrint(printInfo);
			}

		}
	};

	// private void startPrint(String printInfo) {
	// // TODO Auto-generated method stub
	// ServiceManager.getInstence().verifyData("2222222");
	// try {
	// try {
	// JSONArray printTest = new JSONArray();
	//
	// JSONObject json0 = new JSONObject();
	// json0.put("content-type", "txt");
	// json0.put("content", printInfo);
	// json0.put("size", "2");
	// json0.put("position", "left");
	// json0.put("offset", "0");
	// json0.put("bold", "0");
	// json0.put("italic", "0");
	// json0.put("height", "-1");
	//
	// printTest.put(json0);
	// printJson.put("spos", printTest);
	// // 设置底部空3行
	// // Set at the bottom of the empty 3 rows
	// com.pos.sdk.printer.PosPrinter.Parameters parameters =
	// ServiceManager.getInstence().getPrinter()
	// .getParameters();
	// parameters.setPrintGray(5000);
	// parameters.setPrintStep(4000);
	// parameters.setPrintHeatPoint(1000);
	// ServiceManager.getInstence().getPrinter().setParameters(parameters);
	// ServiceManager.getInstence().getPrinter().setPrintGray(2000);
	// ServiceManager.getInstence().getPrinter().printBottomFeedLine(5);
	// ServiceManager.getInstence().getPrinter().print(printJson.toString(),
	// null, printer_callback);
	//
	// } catch (JSONException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// }

	private void startPrint(final String printInfo) {
		try {
			try {
				JSONArray printTest = new JSONArray();

				JSONObject json0 = new JSONObject();
				json0.put("content-type", "txt");

						json0.put("content", printInfo);

				//	json0.put("content", "212123123");
				json0.put("size", "2");
				json0.put("position", "left");
				json0.put("offset", "0");
				json0.put("bold", "0");
				json0.put("italic", "0");
				json0.put("height", "-1");
				printTest.put(json0);
				printJson.put("spos", printTest);
				// 设置底部空3行
				// Set at the bottom of the empty 3 rows
				com.pos.sdk.printer.PosPrinter.Parameters parameters = ServiceManager.getInstence().getPrinter()
						.getParameters();
				parameters.setPrintGray(5000);
				parameters.setPrintStep(4000);
				parameters.setPrintHeatPoint(1000);
				ServiceManager.getInstence().getPrinter().setParameters(parameters);
				ServiceManager.getInstence().getPrinter().setPrintGray(2000);
				ServiceManager.getInstence().getPrinter().printBottomFeedLine(5);
				ServiceManager.getInstence().getPrinter().print(printJson.toString(), null, printer_callback);
				/*JSONObject jsonObject=new JSONObject();
				JSONArray printTest1 = new JSONArray();

				JSONObject json01 = new JSONObject();
				json0.put("content-type", "one-dimension");
				json0.put("content", "11123123");
				json0.put("size", "2");
				json0.put("position", "left");
				json0.put("offset", "0");
				json0.put("bold", "0");
				json0.put("italic", "0");
				json0.put("height", "-1");
				jsonObject.put("spos", printTest1);
				ServiceManager.getInstence().getPrinter().print(jsonObject.toString(), null, printer_callback);*/
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public class TimerCountTools {
		private Date timestart = null;
		private Date timestop = null;
		private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		public TimerCountTools() {

		}

		public void start() {
			timestart = new Date(System.currentTimeMillis());
		}

		public void stop() {
			timestop = new Date(System.currentTimeMillis());
		}

		/**
		 * 返回时间差，毫秒级别 Returns the time difference,Unit: ms
		 * 
		 * @return
		 */
		public long getProcessTime() {
			long mils = timestop.getTime() - timestart.getTime();
			return mils;
		}
	}

}
